package com.songlin.testv2ex.ui;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.songlin.testv2ex.R;
import com.songlin.testv2ex.android_gson_json.HttpUtils;
import com.songlin.testv2ex.data.GlobalData;
import com.songlin.testv2ex.model.Member;
import com.songlin.testv2ex.model.Node;
import com.songlin.testv2ex.model.Topic;
import com.songlin.testv2ex.model.TopicsList;
import com.songlin.testv2ex.ui.adapter.MyPagerAdapter;
import com.songlin.testv2ex.ui.fragment.FirstFragment;
import com.songlin.testv2ex.ui.fragment.SecondFragment;
import com.songlin.testv2ex.ui.fragment.TestFragment;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class MainActivity extends FragmentActivity {

    /*  * 要显示的界面数 *  */
    private static final int NUM_PAGES = 2;

    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragmentArrayList;

    private ImageView cursorPic;    //小长条的图片
    private TextView title_tv1,title_tv2;   //界面的标题卡

    private int cursorX;  //小长条的位移
    private int screenWid;  //屏幕的长度
    private int currIndex;    //当前所在的界面
    private int cursorPicWid;   //小长条动画的宽度
    public SharedPreferences preferences;
    public SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initShared();
        readFromFile(GlobalData.Lastest_Topics, "data.dat");
        System.out.println("GlobalData.Lastest_Topics:" + GlobalData.Lastest_Topics.isEmpty() );
        connectOrNot();
        if(GlobalData.Is_Connected && GlobalData.Lastest_Topics.isEmpty()) {
            readAPI();
            writeToFile(GlobalData.Lastest_Topics, "data.dat");
            writeToFile(GlobalData.Strings_Home,"data1.dat");
            System.out.println(GlobalData.Lastest_Topics.isEmpty());
        } else {
            /** 有待测试*/
            readFromFile(GlobalData.Lastest_Topics,"data.dat");
        }
        setContentView(R.layout.activity_main);
        initTextView();
        initImageView();
        initViewPager();
        /*h = new Handler() {
            @Override
            public void handleMessage(Message message) {
                String s = (String) message.obj;
            }
        };*/
    }

    public void connectOrNot() {
        ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
        boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        if(wifi|internet){
            GlobalData.Is_Connected = true;
            //执行相关操作
        }else{
            GlobalData.Is_Connected = false;
            Toast.makeText(getApplicationContext(),
                    "亲，网络连了么？", Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void initShared() {
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
    }

    public void initTextView() {
        title_tv1 = (TextView) findViewById(R.id.title_1);
        title_tv2 = (TextView) findViewById(R.id.title_2);

        title_tv1.setOnClickListener(new MyOnClickListener(0));
        title_tv2.setOnClickListener(new MyOnClickListener(1));
    }

    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;
        public MyOnClickListener(int i) {
            index = i;
        }
        @Override
        public void onClick(View view) {
            viewPager.setCurrentItem(index);
        }
    }

    public void initImageView() {
        cursorPic = (ImageView) findViewById(R.id.cursor_iv);
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.mipmap.cursor_blue_2);
        cursorPicWid = bitmap.getWidth();   //获取图片宽度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        screenWid = displayMetrics.widthPixels;
        cursorX = (screenWid / NUM_PAGES - cursorPicWid) / 2;
        Matrix matrix = new Matrix();
        matrix.postTranslate(cursorX, 0);
        cursorPic.setImageMatrix(matrix);
    }

    public void readAPI() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                TopicsList topicsList = new TopicsList();
                String url = GlobalData.URL_Latest_Topics;
                String data = HttpUtils.getJsonContent(url);    //从API获取数据
                try {
                    JSONArray jsonArray = new JSONArray(data);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        Topic topicTemp = new Topic();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        topicTemp.id = jsonObject.getInt("id");
                        System.out.println(topicTemp.id);
                        topicTemp.title = jsonObject.getString("title");
                        topicTemp.url  = jsonObject.getString("url");
                        topicTemp.content = jsonObject.getString("content");
                        topicTemp.contentRendered = jsonObject.getString("content_rendered");
                        topicTemp.replies = jsonObject.getInt("replies");

                        JSONObject memberData = jsonObject.getJSONObject("member");
                        Member member = new Member();
                        member.id = memberData.getInt("id");
                        member.username = memberData.getString("username");
                        member.tagline = memberData.getString(("tagline"));
                        member.avatar = memberData.getString("avatar_normal");
                        topicTemp.member = member;

                        JSONObject nodeData = jsonObject.getJSONObject("node");
                        Node node = new Node();
                        node.id = nodeData.getInt("id");
                        node.name = nodeData.getString("name");
                        node.title = nodeData.getString("title");
                        node.titleAlternative = nodeData.getString("title_alternative");
                        node.url = nodeData.getString("url");
                        node.topics = nodeData.getInt("topics");
                        node.avatar = nodeData.getString("avatar_normal");
                        topicTemp.node = node;

                        topicTemp.created = jsonObject.getLong("created");
                        topicTemp.lastModified = jsonObject.getLong("last_modified");
                        topicTemp.lastTouched = jsonObject.getLong("last_touched");
                        topicsList.add(topicTemp);

                        Log.d("- - - Success - - -", " - - - json解析成功 - - - ");
                    }
                    GlobalData.Lastest_Topics = topicsList;
                    for (int i = 0; i < GlobalData.Lastest_Topics.size(); i++) {
                        System.out.println(GlobalData.Lastest_Topics.get(i).created);
                    }
                    Log.d("- - - Success - - -", " - - - GlobalData.Lastest_Topics 更新成功 - - - ");
                } catch (Exception ex) {
                    Log.d("Throws Exception", "From \"public View onCreateView \" in class FirstFragment");
                    ex.printStackTrace();
                }

                url = GlobalData.URL_User_Home;
                data = HttpUtils.getJsonContent(url);    //从API获取数据
                try {
                    JSONObject jsonObject1 = new JSONObject(data);
                    String[] strings = new String[11];
                    strings[0] = jsonObject1.getString("status");
                    strings[1]  = jsonObject1.getString("url");
                    strings[2] = jsonObject1.getString("username");
                    strings[3] = jsonObject1.getString("website");
                    strings[4] = jsonObject1.getString("twitter");
                    strings[5] = jsonObject1.getString("psn");
                    strings[6] = jsonObject1.getString("github");
                    strings[7] = jsonObject1.getString("btc");
                    strings[8] = jsonObject1.getString("location");
                    strings[9] = jsonObject1.getString("tagline");
                    strings[10] = jsonObject1.getString("bio");

                    GlobalData.Strings_Home = strings;
                    Log.d("- - - Success - - -", " - - - json解析成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 更新成功 - - - ");
                    System.out.print(GlobalData.Strings_Home.toString());
                } catch (Exception ex) {
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    Log.d("- - - Success - - -", " - - - strings 失败 - - - ");
                    System.out.print(GlobalData.Strings_Home.toString());
                    ex.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public void writeToFile(Object object, String path) {
        try {
            /*File file =new File(path);*/
            FileOutputStream fileOutputStream = openFileOutput(path, MODE_APPEND);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            objectOutputStream.close();
            System.out.println(" - - - GlobalData.Lastest_Topics 保存成功 - - - ");
            Log.d("- - - Success - - -", " - - - GlobalData.Lastest_Topics 保存成功 - - - ");
        } catch(Exception ex) {
            System.out.println(" - - - GlobalData.Lastest_Topics 保存失败 - - - ");
            System.out.println(" - - - GlobalData.Lastest_Topics 保存失败 - - - ");
            Log.d("Throws Exception", "From \"public void writeToFile(TopicsList topicsList) \" in class MainActivity");
            ex.printStackTrace();
        }
    }

    public void readFromFile(Object object, String path) {
        try {
            FileInputStream fileInputStream = openFileInput(path);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            object = objectInputStream.readObject();
            objectInputStream.close();
            Log.d("- - - Success - - -", " - - - readFromFile(Object object, String path) 成功 - - - ");
        } catch(Exception ex) {
            Log.d("Throws Exception", "From \"public void readFromeFile(Object object, String path) \" in class MainActivity");
            ex.printStackTrace();
        }
    }

    public void initViewPager() {
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        fragmentArrayList = new ArrayList<Fragment>();
        Fragment firstFragment = new FirstFragment();
        Fragment secondFragment = new SecondFragment();
        Fragment thirdFragment = TestFragment.newInstance("Just for a test.");
        fragmentArrayList.add(firstFragment);
        fragmentArrayList.add(secondFragment);
        fragmentArrayList.add(thirdFragment);

        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(),fragmentArrayList);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
    }

    public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private int moveS = screenWid / NUM_PAGES;
        private static final float MIN_SCALE = 0.85F;
        private static final float MIN_ALPHA = 0.5F;

        public void transformPage(View view , float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();

            if ( position < - 1) {  //到了最左边后，不能再向左滑屏
                view.setAlpha(0);
            }   else if (position <= 1 ) {  // 从-1到1；修改默认的幻灯片转换，以缩小页面
                float scaleFactor = Math.max(MIN_SCALE , 1 - Math.abs(position));
                float vertMargin = pageHeight * ( 1 - scaleFactor) / 2;
                float horzMargin = pageWidth * ( 1 - scaleFactor) / 2;
                if ( position < 0 ) {
                    view.setTranslationX(horzMargin - vertMargin / 2);
                }   else {
                    view.setTranslationX( -horzMargin +vertMargin / 2);
                }

                //在0.85f到1之间，页面在滑动切换过程中的缩放
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

                //以下面的大小比例来把旧页面切走
                view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE)/(1 - MIN_SCALE) * ( 1 - MIN_ALPHA));
                cursorMove(viewPager.getCurrentItem());
            }   else {  //到了最右边后，不能再向右边滑屏
                view.setAlpha(0);
            }
        }

        public void cursorMove (int arg0) {
            Animation animation = new TranslateAnimation(currIndex * moveS , arg0 * moveS , 0 ,0);//平移动画
            currIndex = arg0;
            animation.setFillAfter(true);   //设置动画终止时停留在最后一帧，不然会回到没有执行前的状态
            animation.setDuration(500); //设置动画持续时间
            cursorPic.startAnimation(animation);//是用ImageView来显示动画的
        }
    }

    @Override
    /*  * 相当于后退键的监听器 *  */
    public void  onBackPressed() {
        if (viewPager.getCurrentItem() == 0) {
            //如果到了第一个界面，就结束，退出
            super.onBackPressed();
        }   else {
            //往后退一个Fragment
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        }
    }

}
